<#import "/spring.ftl" as spring />
<#import "../layout/defaultLayout.ftl" as layout>
<@layout.defaultLayout styles=["bootstrap-table/bootstrap-table.min.css",
"bootstrap-validator/css/bootstrapValidator.css",
"bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css",
"jquery/tree-multiselect/jquery.tree-multiselect.min.css"]
scripts=["bootstrap-table/bootstrap-table.min.js",
"bootstrap-table/locale/bootstrap-table-zh-CN.min.js",
"bootstrap-validator/validator.js",
"jquery/serializejson/jquery.serializejson.min.js",
"util/jquery-dateFormat.min.js",
"bootstrap-table/extensions/export/bootstrap-table-export.min.js",
"bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js",
"bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js",
"bootstrap-table/extensions/editable/bootstrap-table-editable.js",
"x-editable/bootstrap3-editable/js/bootstrap-editable.js",
"bootstrap-validator/js/bootstrapValidator.js",
"util/tableExport.js","util/moment.js",
"jquery/tree-multiselect/jquery.tree-multiselect.js"]>
<style>
body{
	padding-top:10px;
}
div.tree-multiselect{
	border:none;
}
.container{
	padding:15px;width:90%;
}
.panelselect{
	background-color: white;
	height: 400px;
	overflow:auto;
	border:2px solid #D8D8D8;
	padding-left:0px;
	padding-right:0px;
}
.panelHeight{
	height:200px;
	float:left;
    width: 50%;
}
.spanblock{
	background-color: gray;
	width:100%;
	height: 30px;
	line-height:30px;   
	color:white;
	padding-left:5px;
}
.spanblock > div{
	float:right;
	padding-right:5px;
	padding-bottom:2px;
	top:3px;
}
.columnPanel{
	height:100px;	
	overflow:auto;
}
#filterShow .popover-content .editableform > div{
	display:inline;
}
#filterShow .popover-content .editableform .editable-input{
	float: left;
    width: 130px;
}
#filterShow .popover-content .editableform .editable-buttons{
	float: right;
}
#filterShow .popover-content .editableform .editable-input input{
	width: 120px;
}
#filterShow .popover-content .editableform .editable-input select{
	width: 120px;
}
#filterShow td,#filterShow th {
    min-width: 16.67%;
}
#columnShow .popover-content .editableform > div{
	display:inline;
}
#columnShow .popover-content .editableform .editable-input{
	float: left;
    width: 100px;
}
#columnShow .popover-content .editableform .editable-buttons{
	float: right;
}
#columnShow .popover-content .editableform .editable-input input{
	width: 90px;
}
#columnShow .popover-content .editableform .editable-input select{
	width: 90px;
}
#relationShow .popover-content .editableform > div{
	display:inline;
}
#relationShow .popover-content .editableform .editable-input{
	float: left;
    width: 130px;
}
#relationShow .popover-content .editableform .editable-buttons{
	float: right;
}
#relationShow .popover-content .editableform .editable-input input{
	width: 120px;
}
#relationShow .popover-content .editableform .editable-input select{
	width: 120px;
}
tr td{
	cursor:pointer;
}
table td, table th {
    min-width: 80px;
}
.tableHight{
	height:200px;
}
</style>
<div class="container">
	<div class="row clearfix">
		<div class="col-md-4 column panelselect dataView">
		<div class="spanblock"><@spring.message "sqlconfig.dataView"/></div>
			<select id="tableShowSelect" multiple="multiple">
			 	
			</select>
		</div>	
		<div class="col-md-8 column">
			<div class="spanblock"><@spring.message "sqlconfig.selectedCol"/><div class="btn-group btn-group-xs"><button type="button" class="btn btn-default"><i class="glyphicon glyphicon-remove"></i></button></div></div>
			<div class="columnPanel">
				<table id="columnShow" data-classes="table table-hover table-striped" 
						data-pagination="false"  data-side-pagination="client" data-method="post" >
						           
				</table>
			</div>
			<div class="spanblock"><@spring.message "sqlconfig.relation"/><div class="btn-group btn-group-xs">
			<button class="btn btn-default" id ="relationInsert">
					<i class="glyphicon glyphicon-plus"></i>
				</button>
			<button type="button" id="relationRemove" class="btn btn-default"><i class="glyphicon glyphicon-remove"></i></button></div></div>
			<div class="columnPanel">
				<table id="relationShow" data-classes="table table-hover table-striped" 
						data-pagination="false"  data-side-pagination="client" data-method="post" >
						           
				</table>
			</div>
			
			<div class="spanblock"><@spring.message "sqlconfig.appFilter"/><div class="btn-group btn-group-xs">
			<button id="filterInsert" class="btn btn-default">
					<i class="glyphicon glyphicon-plus"></i>
				</button>
			<button type="button" id="filterRemove" class="btn btn-default"><i class="glyphicon glyphicon-remove"></i></button></div></div>
			<div class="columnPanel">
				<table id="filterShow" data-classes="table table-hover table-striped" 
						data-pagination="false"  data-side-pagination="client" data-method="post" >
						           
				</table>
			</div>
		</div>
	</div>
	<div class="row clearfix">
		<div class="col-md-12 column">
			<div class="spanblock"><@spring.message "sqlconfig.searchResult"/></div>
			<div class="columnPanel tableHight">
				<table id="dataShow" data-classes="table table-hover table-striped"  data-toggle="table">
						           
				</table>
			</div>
		</div>
	</div>
	<div style="float:right">
		<button type="button" id="queryResult" class="btn btn-success"><@spring.message "sqlconfig.searchResult"/></button>
		<button type="button" id="configSubmit" class="btn btn-success"><@spring.message "sqlconfig.sure"/></button>
	</div>
</div>
<!-- 模态框（Modal） -->
<div class="modal fade" id="configColPage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog" style="width:700px;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
					<@spring.message "sqlconfig.colLink"/>
				</h4>
			</div>
			<div class="modal-body">
				<div class="container">
					<div class="row clearfix">
						<div class="col-md-6 column panelselect panelHeight leftColsSelect">
							<!-- <select id="leftColsSelect" multiple="multiple">
			 	
							</select> -->
						</div>
						<div class="col-md-6 column panelselect panelHeight rightColsSelect">
							<!-- <select id="rightColsSelect" multiple="multiple">
			 	
							</select> -->
						</div>
					</div>
					<br/>
					<div class="row clearfix" >
						<form class="form-inline" role="form" style="text-align: center;">
							<input type="text" name="leftColCode" id="leftColCode" class="form-control" />
							<select name="symbol" id="symbol">
								<option value="=">=</option>
								<option value=">">></option>
								<option value=">=">>=</option>
								<option value="<">&lt;</option>
								<option value="<=">&lt;=</option>
							</select>
							<input type="text" name="rightColCode" id="rightColCode" class="form-control" />
							<button id="colSure" type="button" class="btn btn-success" ><@spring.message "sqlconfig.sure"/></button>
						</form>
					</div>
					<br/>
					<div class="row clearfix" >
						<div id="toolbar">
					        <button id="removeCols" class="btn btn-success" >
					            <i class="glyphicon glyphicon-remove"></i><@spring.message "button.delete"/>
					        </button>	
					        	        
					    </div>
						<table id="colsRelationConf" data-classes="table table-hover table-striped" 
							data-pagination="false"  data-side-pagination="client" data-method="post" data-toolbar="#toolbar" >
							           
						</table>
					</div>
				</div>
				
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal"><@spring.message "button.shutdown"/>
				</button>
				<button type="button" class="btn btn-primary" id="dialogSure">
					<@spring.message "sqlconfig.sure"/>
				</button>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>

<script>
	var dataShowTab = $("#dataShow");
	var columnShowTab = $("#columnShow");
	var filterShowTab = $("#filterShow");
	var relationShowTab = $("#relationShow");
	var colsRelationConf = $("#colsRelationConf"); 
	var options = {showSectionOnSelected:false,startCollapsed:true,hideSidePanel:true};
	var modelOptions = {showSectionOnSelected:false,startCollapsed:true,hideSidePanel:true,startCollapsed:true,collapsible:false};
	
	var selectItems = '';
	var dataKey = 10000;
	var colObjList = [];
	var colFlag = 0;//对字段列表执行标记
	var colLinkTableFlag = 1;//为表建立索引
	var dealRowIdx = 0;//存储关系table中处理的index
	var dealRowData;//存储关系table中row数据
	var filterShowIndex = 1;//建立序列
	var relationShowIndex = 1;//建立序列
	var assembleSqlStr= "";//sql存储
	window.isParameterEvents = {
	        'change :checkbox': function (e, value, row, index) {
	            row.isParameter = $(e.target).prop('checked');
	            filterShowTab.bootstrapTable('updateRow', {
	                index: index,
	                row: row        
	            });
	        }  	
	    };
	function checkFormatter(value) {
        var checked = value ? 'checked' : '';
        return '<input type="checkbox" ' + checked + ' />';
    }
	function queryParams(params) {
		obj.offset = params.offset;
		obj.limit = params.limit;
		return {'offset':params.offset,'limit':params.limit,'assembleSql':assembleSqlStr};
	}
	function sectionTileClick(event){
		//filter modal dialog
		parentTarget = $(event.target).closest('#dataView');
		if (parentTarget[0] != null){
			/* alert("111") */
		}
		var tableTitle = event.target;
		var nextEle = event.target.nextElementSibling;
		if ($(tableTitle).attr("clickflag") == '1'){
			return ;
		}
		if ($(nextEle).hasClass("item")){
			var tableName = $(nextEle).attr("data-value");
			$.ajax({
	    		url:'${request.contextPath}/report/sqlConfig/getColsByTableName',
		        type:'POST',
		        data:JSON.stringify(tableName),
		        contentType: 'application/json',
		        dataType:'json',
		        success:function(data){
		        	var items = $(tableTitle).parent().find(".item");
		    		items.remove();
		        	optionItems = "";
		        	$.each(data,function(i,colMap){
		        		++dataKey;
		        		optionItems = optionItems + "<div class='item' data-table='"+tableName+"' data-key='"+dataKey+"' data-value='"+colMap.COLUMN_NAME+"' style='display: block;'><input class='option' onchange='colClick(event);' type='checkbox' id='treemultiselect_"+dataKey+"'><label for='treemultiselect_"+dataKey+"'>"+colMap.COLUMN_NAME+"</label></div>";
		        	})
		        	$(tableTitle).attr("clickflag","1");
		        	$(tableTitle).parent().append(optionItems);
		        }
	    	});
		}else{
			return false;
		}
	} 
	
	function titleCheckClick(event){
		/* parentTarget = $(event.target).closest('.dataView');
		if (parentTarget[0] != null){
			alert("222")
		} */
		var checkSection = $(event.target).parent().parent();
		var itemCheckboxs = checkSection.find(".item");
		if ($(event.target).prop("checked")){
			checkSection.find("input").attr('checked',true);
			$.each(itemCheckboxs,function(i,itemCheckbox){
				dataTable = $(itemCheckbox).attr('data-table');
				dataValue = $(itemCheckbox).attr('data-value');
				var colDataObj = new Object();
				colDataObj.itemTable = dataTable;
				colDataObj.itemValue = dataValue;
				colObjList.push(colDataObj);
			});
		}else {
			checkSection.find("input").siblings().attr('checked',false);
			var checkTable ="";
			if (itemCheckboxs.length > 0){
				checkTable = $(itemCheckboxs[0]).attr('data-table');
			}
			removeColList = [];
			$.each(colObjList,function(i,colMap){
				if (colMap['itemTable'] == checkTable){
					colObjList[i] = null;
					//colObjList.splice(i,1);
				}
			});
			for (var j=colObjList.length-1;j >= 0 ;j--){
				if (colObjList[j] == null){
					colObjList.splice(j,1);
				}
			}
		} 
		
		columnShowFreshTable(colObjList);
		
	}
	
	function collapseClick(event){
		var parentTitle = $(event.target).parent();
		
		if (parentTitle.parent().parent().hasClass("selections")){
			return false;
		}
		if (parentTitle.attr('clickflag') == '0'){	
			parentTitle.click();
		}
	}
	function colClick(event){
		dataTable = $(event.target).parent().attr('data-table');
		dataValue = $(event.target).parent().attr('data-value');
		if ($(event.target).prop('checked')){
			var colObj = new Object();
			colObj.itemTable = dataTable;
			colObj.itemValue = dataValue;
			colObjList.push(colObj);
		}else {
			$.each(colObjList,function(i,colMap){
				if (colMap['itemTable'] == dataTable && colMap['itemValue'] == dataValue){
					colObjList.splice(i,1);
					return false;
				}
			});
		} 
		columnShowFreshTable(colObjList);
	}
	
	function leftRelaCheck(event){
		leftSection = $(event.target).closest(".leftSection");
		leftItems = leftSection.find("input:checked");
		if (leftItems.length > 0){
		/* 	alert("只能选择一个");
		}else if (leftItems.length = 1){ */
			leftItem = $(leftItems[0]).parent(".item");
			$("#leftColCode").val(leftItem.attr("data-table")+"."+leftItem.attr("data-value"));
		}else {
			$("#leftColCode").val("");
		}
	}
	
	function rightRelaCheck(event){
		rightSection = $(event.target).closest(".rightSection");
		rightItems = rightSection.find("input:checked");
		if (rightItems.length > 0){
		/* 	alert("只能选择一个");
		}else if (leftItems.length = 1){ */
			rightItem = $(rightItems[0]).parent(".item");
			$("#rightColCode").val(rightItem.attr("data-table")+"."+rightItem.attr("data-value"));
		}else {
			$("#rightColCode").val("");
		}
	}
	
	function columnShowFreshTable(colObjList){
    	var datas=[];
    	$.each(colObjList,function(i,colMap){
    		row = {};
    		row.columnCode = colMap.itemTable+"."+colMap.itemValue;
    		row.aggregateFunc = '';
    		datas.push(row);
    	});
    	if (colFlag == 0){
    		columnShowTab.bootstrapTable({
                data: datas,
                columns:[{
                    field: 'columnCode',
                    title: "<@spring.message 'column.columnCode'/>",
                    halign: 'center',
                    width: '60',
                    align: 'center'
                },{
                	field:'aggregateFunc',
                	title:"<@spring.message 'column.aggregateFunc'/>",
                	halign: 'center',
                	align: 'center',
                	width: '100',
                	editable: {
                        type: 'select',
                        source: [
           				 {value: '', text: "<@spring.message 'select.tip'/>"},
                            {value: 'COUNT', text: 'COUNT'},
                            {value: 'SUM', text: 'SUM'},
                            {value: 'AVG', text: 'AVG'},
                            {value: 'MAX', text: 'MAX'},
                            {value: 'MIN', text: 'MIN'},
                            {value: 'DISTINCT', text: 'DISTINCT'}
                        ] }
                }]
               
        	});
    	}else{
    		//columnShowTab.bootstrapTable('destroy');
    		columnShowTab.bootstrapTable('refreshOptions',{
                data: datas,
                columns:[{
                    field: 'columnCode',
                    title: "<@spring.message 'column.columnCode'/>",
                    halign: 'center',
                    width: '60',
                    align: 'center'
                },{
                	field:'aggregateFunc',
                	title:"<@spring.message 'column.aggregateFunc'/>",
                	halign: 'center',
                	align: 'center',
                	width: '100',
                	editable: {
                        type: 'select',
                        source: [
           				 {value: '', text: "<@spring.message 'select.tip'/>"},
                            {value: 'COUNT', text: 'COUNT'},
                            {value: 'SUM', text: 'SUM'},
                            {value: 'AVG', text: 'AVG'},
                            {value: 'MAX', text: 'MAX'},
                            {value: 'MIN', text: 'MIN'},
                            {value: 'DISTINCT', text: 'DISTINCT'}
                        ] }
                }]
        	});
    	}
    	colFlag ++;
	}
	
    $(function(){	
    	$.ajax({
    		url:'${request.contextPath}/report/sqlConfig/getTableAndView',
	        type:'POST',
	        contentType: 'application/json',
	        dataType:'json',
	        success:function(data){
	        	selectItems = '';
	        	var tablesList = data.tablesList;
	        	var viewsList = data.viewsList;
	        	$.each(tablesList,function(i,tableMap){
	        		//selectItems =selectItems + "<option value='"+tableMap.TABLE_NAME+"' data-section='table' data-index='' data-description=''>"+tableMap.TABLE_NAME+"</option>"; 
	        		selectItems =selectItems + "<option value='"+tableMap.TABLE_NAME+"' data-section='table/"+tableMap.TABLE_NAME+"' data-index='' data-description=''><@spring.message 'column.fillEmpty' /></option>";   
	        	})
	        	$.each(viewsList,function(i,viewMap){
	        		//selectItems = selectItems + "<option value='"+viewMap.VIEW_NAME+"' data-section='view' data-index='' data-description=''>"+viewMap.VIEW_NAME+"</option>"; 
	        		selectItems =selectItems + "<option value='"+viewMap.VIEW_NAME+"' data-section='view/"+viewMap.VIEW_NAME+"' data-index='' data-description=''><@spring.message 'column.fillEmpty' /></option>"; 
	        	})
	        	$("select#tableShowSelect").append(selectItems);
	        	$("select#tableShowSelect").treeMultiselect(options); 
	        }
    	}); 
    	
    	relationShowTab.bootstrapTable({
    		columns: [{
                field: '',
                title: "",
                halign: 'center',
                width: '30',
                checkbox:true,
                align: 'center'
            },{
                field: 'leftTable',
                title: "<@spring.message 'column.leftTable' />",
                halign: 'center',
                width: '60',
                editable:true,
                align: 'center'
            },{
            	field:'linkType',
            	title:"<@spring.message 'column.linkType' />",
            	halign: 'center',
            	align: 'center',
            	width: '100',
            	editable: {
                    type: 'select',
                    source: [
                        {value: 'LEFT JOIN', text: 'LEFT JOIN'},
                        {value: 'RIGHT JOIN', text: 'RIGHT JOIN'},
                        {value: 'INNER JOIN', text: 'INNER JOIN'}
                    ] }
            },{
                field: 'rightTable',
                title: "<@spring.message 'column.rightTable' />",
                halign: 'center',
                width: '60',
                editable:true,
                align: 'center'
            },{
                field: 'linkCols',
                title: "<@spring.message 'column.linkCols' />",
                halign: 'center',
                width: '60',
                align: 'center'
            },{
                field: 'id',
                title: "id",
                visible:false
            }
            ]
    	});
    	
    	colsRelationConf.bootstrapTable({
    		columns: [{
    			field: '',
                title: "",
                halign: 'center',
                width: '30',
                checkbox:true,
                align: 'center'
            },{
                field: 'idx',
                title: "<@spring.message 'sqlconfig.idx' />",
                halign: 'center',
                align: 'center'
            },{
                field: 'colLinks',
                title: "<@spring.message 'sqlconfig.collink' />",
                halign: 'center',
                align: 'center'
            }]
    	})
    	
    	$("#filterInsert").click(function(){
    		filterShowTab.bootstrapTable('insertRow', {
                index: 1,
                row: {
                	id:filterShowIndex++,
                	columnCode: '',
                	operation: '=',
                	value: '',
                	usage:'WHERE',
                	isParameter:false
                }
            });
    	});
    	
    	$("#relationInsert").click(function(){
    		relationShowTab.bootstrapTable('insertRow', {
                index: 1,
                row: {
                	id:relationShowIndex++,
                	leftTable: '',
                	linkType: 'LEFT JOIN',
                	rightTable: '',
                	linkCols:"<a>Empty</a>"
                }
            });
    	});
    	/* <a style＝'cursor:pointer' data-toggle='modal' data-target='#configColPage'>Empty</a> */
    	$("#relationRemove").click(function(){
    		ids = $.map(relationShowTab.bootstrapTable('getSelections'), function (row) {
                return row.id;
            });
    		relationShowTab.bootstrapTable('remove', {
                field: 'id',
                values: ids
            });
    	});
    	
    	$("#filterRemove").click(function(){
    		ids = $.map(filterShowTab.bootstrapTable('getSelections'), function (row) {
                return row.id;
            });
    		filterShowTab.bootstrapTable('remove', {
                field: 'id',
                values: ids
            });
    	});
    	
    	$("#colSure").click(function(){
    		leftColCodeVal = $("#leftColCode").val();
    		rightColCodeVal = $("#rightColCode").val();
    		symbolVal = $("#symbol").val();
    		colsRelationConf.bootstrapTable('insertRow', {
                index: 1,
                row: {
                	idx: colLinkTableFlag++,
                	colLinks: leftColCodeVal+symbolVal+rightColCodeVal
                }
            });
    		//init configColPage dialog
    		$("#leftColCode").val("");
    		$("#rightColCode").val("");
    		$("#configColPage").find("input[type='checkbox']").prop("checked",false);
    	});
    	
    	$("#dialogSure").click(function(){
    		var relConfTableData = colsRelationConf.bootstrapTable('getData');
    		colLinksArray = $.map(relConfTableData, function (row) {
                return row.colLinks;
            });
    		dealRowData.linkCols = "<a>"+colLinksArray.join(",")+"</a>";
    		relationShowTab.bootstrapTable('updateRow', {
                index: dealRowIdx,
                row: dealRowData        
            });
    		$('#configColPage').modal('hide');
    	});
    	
    	$("#removeCols").click(function(){
    		idxs = $.map(colsRelationConf.bootstrapTable('getSelections'), function (row) {
                return row.idx;
            });
    		colsRelationConf.bootstrapTable('remove', {
                field: 'idx',
                values: idxs
            });
    	});
    	
    	function generateSql(){
    		columnShowData =  columnShowTab.bootstrapTable('getData');
    		filterShowData =  filterShowTab.bootstrapTable('getData');
    		relationShowData =  relationShowTab.bootstrapTable('getData');
    		columnStr = "";
    		filterWhereStr = "";
    		filterHavingStr = "";
    		relationStr = "";
    		//处理字段列表
    		$.each(columnShowData,function(i,columnShowMap){
    			if (columnShowMap.aggregateFunc == ""){
    				columnStr = columnStr + columnShowMap.columnCode +",";
    			}else {
    				columnStr = columnStr + columnShowMap.aggregateFunc + "("+columnShowMap.columnCode+"),";
    			}
    		});
    		columnStr = columnStr.substring(0,columnStr.length-1);
    		//处理查询条件
			$.each(filterShowData,function(i,filterShowMap){
				if (filterShowMap.isParameter){
					assembleVal = "";
					if (filterShowMap.operation == 'LIKE'){
						assembleVal = " '%#" +  filterShowMap.columnCode.split(".")[1] +"#%' ";
					}else {
						assembleVal = " '#" +  filterShowMap.columnCode.split(".")[1] +"#' "
					}
					if (filterShowMap.usage == 'WHERE'){
						filterWhereStrmu = filterWhereStr !=""?filterWhereStr+" AND ":" ";
						filterWhereStr = filterWhereStrmu + filterShowMap.columnCode +" "+ filterShowMap.operation + assembleVal;
					}else if(filterShowMap.usage == 'HAVING'){
						filterHavingStrmu = filterHavingStr !=""?filterHavingStr+" AND ":" ";
						filterHavingStr = filterHavingStrmu + filterShowMap.columnCode +" "+ filterShowMap.operation + assembleVal;
					}
				}else {
					assembleVal = "";
					if (filterShowMap.operation == 'LIKE'){
						assembleVal = " '%" +  filterShowMap.value +"%' ";
					}else {
						assembleVal = " '" +  filterShowMap.value +"' "
					}
					if (filterShowMap.usage == 'WHERE'){
						filterWhereStrmu = filterWhereStr !=""?filterWhereStr+" AND ":" ";
						filterWhereStr = filterWhereStrmu + filterShowMap.columnCode +" "+ filterShowMap.operation + assembleVal;
					}else if(filterShowMap.usage == 'HAVING'){
						filterHavingStrmu = filterHavingStr !=""?filterHavingStr+" AND ":" ";
						filterHavingStr = filterHavingStrmu + filterShowMap.columnCode +" "+ filterShowMap.operation + assembleVal;
					}
				}
			});
    		//处理表关联关系
			$.each(relationShowData,function(i,relationShowMap){
				linkStr = relationShowMap.linkCols.replace(new RegExp(/(<a>)/g),'').replace(new RegExp(/(<\/a>)/g),'');
				linkArray = linkStr.split(",");
				linkStrAssemble = "";
				for (i =0;i<linkArray.length;i++){
					linkStrAssemblemu = linkStrAssemble !=""?linkStrAssemble+" AND ":" ";
					linkStrAssemble = linkStrAssemblemu + linkArray[i];
				}
				relationStrmu = relationStr !=""?relationStr+" ":" "
				relationStr = relationStrmu + relationShowMap.leftTable +"  "+ relationShowMap.linkType + "  "+relationShowMap.rightTable +" ON " + linkStrAssemble +" ";
			});
    		assembleSql = "SELECT " + columnStr + " FROM " + relationStr +" where "+ filterWhereStr;
    		tableArray = [];
    		$.each(colObjList,function(i,colMap){
    			insertFlag = 0;
    			for (j in tableArray){
    				if (tableArray[j] == colMap.itemTable){
    					insertFlag = 1;
    					break;
    				}
    			}
    			if (insertFlag == 0){
    				tableArray[tableArray.length] = colMap.itemTable;
    			}
			});
    		//对表替换别名
    		for (j in tableArray){
    			regStr = tableArray[j];
    			regExpression = new RegExp(regStr,"g");
    			regExpression2 = new RegExp(regStr+" ","g");
    			assembleSql = assembleSql.replace(regExpression2,"mark");//tableArray[j]+" "+'T'+j+" "
    			assembleSql = assembleSql.replace(regExpression,'T'+j);
    			regExpression3 = new RegExp("mark","g");
    			assembleSql = assembleSql.replace(regExpression3,tableArray[j]+" "+'T'+j+" ");
    		}
    		assembleSqlStr = assembleSql;
    	}
    	
    	$("#configSubmit").click(function(){
    		generateSql();
    	})
    	
    	$('#configColPage').on('show.bs.modal', function () {
    		  
    	})
    	
    	
    	relationShowTab.on('click-cell.bs.table', function (e,field, value, row, $element) { 
    		if (field != 'linkCols'){
    			return false;
    		}
    		dealRowIdx = $element.parent().attr("data-index");
    		dealRowData = row;
    		//置空
    		$(".leftColsSelect").empty();
        	$(".rightColsSelect").empty();
    		cellLeftTable = row.leftTable;
    		cellRightTable = row.rightTable;
    		if (cellLeftTable == "" || cellRightTable == ""){
    			alert("<@spring.message 'sqlconfig.tableNotNull' />");
    			return false;
    		}
    		$.ajax({
    			url:'${request.contextPath}/report/sqlConfig/listCols',
		        type:'POST',
		        data:JSON.stringify({"leftTable":cellLeftTable,"rightTable":cellRightTable}),
		        contentType: 'application/json',
		        dataType:'json',
		        success:function(data){
		        	leftTableColsList = data.leftTableColsList;
		        	rightTableColsList = data.rightTableColsList;
		        	//beforeText = "<div class='tree-multiselect'><div class='selections no-border'><div class='section'>";
		        	afterText = "</div></div></div>";
		        	leftSelectItems = "";
		        	rightSelectItems = "";
		        	leftFlag = 0;
		        	rightFlag =0;
		        	$.each(leftTableColsList,function(i,leftColsMap){
		        		if (leftFlag == 0){
		        			leftSelectItems = "<div class='tree-multiselect'><div class='selections no-border'><div class='section leftSection'>" + "<div class='title' clickflag='0' >"+leftColsMap.TABLE_NAME+"</div>";
		        		}
		        		leftSelectItems =leftSelectItems + "<div class='item' data-key='0' data-table="+leftColsMap.TABLE_NAME+" data-value="+leftColsMap.COLUMN_NAME+"><input class='option' type='checkbox' onchange='leftRelaCheck(event);' id='treemultiselect-left-"+leftFlag+"'><label for='treemultiselect-left-"+leftFlag+"'>"+leftColsMap.COLUMN_NAME+"</label></div>"
		        		leftFlag ++;
		        	})
		        	$.each(rightTableColsList,function(i,rightColsMap){
		        		if (rightFlag == 0){
		        			rightSelectItems = "<div class='tree-multiselect'><div class='selections no-border'><div class='section rightSection'>" + "<div class='title' clickflag='0' >"+rightColsMap.TABLE_NAME+"</div>";
		        		}
		        		rightSelectItems =rightSelectItems + "<div class='item' data-key='0' data-table="+rightColsMap.TABLE_NAME+" data-value="+rightColsMap.COLUMN_NAME+"><input class='option' type='checkbox' onchange='rightRelaCheck(event);' id='treemultiselect-right-"+rightFlag+"'><label for='treemultiselect-right-"+rightFlag+"'>"+rightColsMap.COLUMN_NAME+"</label></div>"
		        		rightFlag ++;
		        	})
		        	$(".leftColsSelect").append(leftSelectItems+afterText);
		        	$(".rightColsSelect").append(rightSelectItems+afterText);
		        	$('#configColPage').modal('show');
		        }
    		}) 
    	});
    	
    	filterShowTab.bootstrapTable({
            columns: [{
                field: 'id',
                title: "id",
                visible:false
            },{
                field: '',
                title: "",
                halign: 'center',
                width: '30',
                checkbox:true,
                align: 'center'
            },{
                field: 'columnCode',
                title: "<@spring.message 'column.columnCode' />",
                halign: 'center',
                width: '30',
                editable:true,
                align: 'center'
            },{
            	field:'operation',
            	title:"<@spring.message 'column.operation' />",
            	halign: 'center',
            	align: 'center',
            	width: '100',
            	editable: {
                    type: 'select',
                    source: [
                        {value: '>', text: '>'},
                        {value: '=', text: '='},
                        {value: '<', text: '<'},
                        {value: '>=', text: '>='},
                        {value: '<=', text: '<='},
                        {value: 'LIKE', text: 'LIKE'}
                    ] }
            },{
            	field:'value',
            	title:"<@spring.message 'column.value' />",
            	halign: 'center',
            	align: 'center',
            	editable:true,
            	width: '40'
            },{
            	field:'usage',
            	title:"<@spring.message 'column.usage' />",
            	halign: 'center',
            	align: 'center',
            	width: '100',
            	editable: {
                    type: 'select',
                    source: [
                        {value: 'WHERE', text: "<@spring.message 'sqlconfig.whereSubSentence' />"},
                        {value: 'HAVING', text: "<@spring.message 'sqlconfig.havingSubSentence' />"}
                    ]}
            },{
            	field:'isParameter',
            	title: "<@spring.message 'column.parameter' />",
            	halign: 'center',
            	align: 'center',
            	width: '40',
            	events:"isParameterEvents",
            	formatter:'checkFormatter'
            }]
        });
    	
    	$("#queryResult").click(function(){
    		generateSql();
    		$.ajax({
    	        url:'${request.contextPath}/report/sqlConfig/data',
    	        type:'POST',
    	        contentType: 'application/json',
    	        data:JSON.stringify({'offset':0,'limit':10,'assembleSql':assembleSqlStr}),
    	        dataType:'json',
    	        success:function(data){
    	        	columns = [], datas = [];  
    	        	if (data.rows){
    	    			var rowMap = data.rows[0];
    	    			for (var key in rowMap){
    	    				if (key != 'IDX'){
    	    					columns.push({
    		                        field: key,                   
    		                        title: key,
    		                        sortable: true
    		                    });
    	    				}
    	    				
    	    			}
    	    			datas = data.rows;
    	    		}else {
    	    			alert("<@spring.message 'sqlconfig.sqlHaveProblem' />"+assembleSqlStr);
    	    		}
    	        	dataShowTab.bootstrapTable('refreshOptions',{
    	        		columns:columns,
    	        		data:datas,
    	        		pagination: true,
    	        		sidePagination: 'client',
    	        		 pageList: [10]
    	        	});  
    	        }
    	})
    	})
    });
</script>
</@layout.defaultLayout>